import {
    Card,
    Breadcrumb,
    Form,
    Input,
    Radio,
    Space,
    Button,
    message,
    Upload,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import Channel from 'components/channel/index';
import axios from 'utils/axios';
import styles from './index.module.scss';
import { getArticleById, issueArticle, putArtcileById } from 'api/articles';
import Modal from 'antd/lib/modal/Modal';

export default class Issue extends Component {
    state = {
        fileList: [],
        type: 0,
        previewImageSrc: '',
        id: this.props.match.params.id,
    };
    // 图片上传校验
    handleBeforeUploadImages = (file) => {
        const whiteUploadImage = ['image/jpg', 'image/jpeg', 'image/png'];
        if (whiteUploadImage.includes(file.type)) {
            if (file.size > 100000) {
                message.warning('上传图片类型过大');
                return Upload.LIST_IGNORE;
            }
            return Promise.resolve(file);
        } else {
            message.warning('只能上传 jpg、png、jpeg 图片类型的文件！');
            return Upload.LIST_IGNORE;
        }
    };
    // 获取图片数据
    handleUploadImages = ({ fileList }) => {
        this.setState({ fileList });
    };
    // 发布文章
    onFinish = () => {
        this.issueArtcile();
    };
    // 利用 生命钩子 回显数据
    async componentDidMount () {
        // 判断是否有id,如果有 id ,则根据 id获取文章数据
        if (this.state.id) {
            const artcileDetails = await getArticleById(this.state.id);
            // console.log('------->', artcileDetails);

            // const fileList = artcileDetails.cover.images
            // 	.map((imgSrc, index) => {
            // 		let url = '';
            // 		if (index % 2 === 0) {
            // 			url =
            // 				imgSrc.includes(',') || imgSrc.includes('http')
            // 					? imgSrc
            // 					: `${artcileDetails.cover.images[index]},${
            // 							artcileDetails.cover.images[index + 1]
            // 					  }`;
            // 			return { url };
            // 		} else {
            // 			if (imgSrc.includes('http')) {
            // 				return { url: imgSrc };
            // 			}
            // 		}
            // 	})
            // 	.filter((url) => url && url);
            const fileList = artcileDetails.cover.images.map((url) => ({
                url,
            }));
            const type = fileList.length > 1 ? 3 : fileList.length || 0;
            this.issueForm.setFieldsValue({
                ...artcileDetails,
                type,
            });
            this.setState({ fileList, type });
        }
    }
    // 封装发布文章函数
    issueArtcile = async (draft) => {
        try {
            const artcileContext = await this.issueForm.validateFields();
            const { fileList, type } = this.state;
            // 判断用户上传的图片 与 选择上传图片个数是否相等
            if (fileList.length < this.state.type) {
                message.warning('图片上传数量不符合！');
                return false;
            }
            // 获取图片的 url路径
            const images = fileList.map(
                (image) => image.response.data.url || image.url
            );
            // 收集数据
            artcileContext['cover'] = {
                type,
                images,
                title: artcileContext.title,
            };
            // 判断用户是否在编辑( 有 id,则表示用户在编辑内容,没有,则新增)
            if (this.state.id) {
                draft
                    ? await putArtcileById(
                        { ...artcileContext, id: this.state.id },
                        true
                    )
                    : await putArtcileById({
                        ...artcileContext,
                        id: this.state.id,
                    });
            } else {
                draft
                    ? await issueArticle(artcileContext, true)
                    : await issueArticle(artcileContext);
            }
            // 提示用户
            message.success('ok');
            // 清除表单数据
            // await this.issueForm.resetFields();
            // 清除图片数组
            // await this.setState({ fileList: [], type: 0 });
            // 跳转页面
            this.props.history.push('/context');
        } catch ({ message: error }) {
            message.error('发布失败');
        }
    };
    // 放大封面图片
    handlePreview = (file) => {
        // console.log('1234567', file);
        const previewImageSrc = file.url || file.thumbUrl;
        this.setState({ previewImageSrc });
    };
    render () {
        const { previewImageSrc, id } = this.state;
        const baseURL = axios.defaults.baseURL;
        return (
            <div className={styles.issue}>
                <Card
                    title={
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>
                                <Link to="/overview">首页</Link>
                            </Breadcrumb.Item>
                            {id ? (
                                <Breadcrumb.Item>编辑文章</Breadcrumb.Item>
                            ) : (
                                <Breadcrumb.Item>发布文章</Breadcrumb.Item>
                            )}
                        </Breadcrumb>
                    }
                >
                    <Form
                        ref={(c) => (this.issueForm = c)}
                        labelCol={{ span: 4 }}
                        autoComplete="off"
                        initialValues={{ type: 0 }}
                        onFinish={this.onFinish}
                    >
                        <Form.Item
                            label="标题"
                            name="title"
                            rules={[
                                { required: true, message: '请输入文章标题' },
                            ]}
                        >
                            <Input
                                placeholder="请输入文章标题"
                                style={{ width: 400 }}
                            />
                        </Form.Item>
                        <Form.Item
                            label="频道"
                            name="channel_id"
                            rules={[
                                { required: true, message: '请选择文章频道' },
                            ]}
                        >
                            <Channel></Channel>
                        </Form.Item>
                        <Form.Item label="封面">
                            <Form.Item name="type">
                                <Radio.Group
                                    onChange={(e) =>
                                        this.setState({ type: e.target.value })
                                    }
                                >
                                    <Radio value={0}>无图</Radio>
                                    <Radio value={1}>单图</Radio>
                                    <Radio value={3}>三图</Radio>
                                    {/* <Radio value={-1}>自动</Radio> */}
                                </Radio.Group>
                            </Form.Item>
                            <div className="upload-list">
                                {this.state.type !== 0 && (
                                    <Upload
                                        listType="picture-card"
                                        name="image"
                                        accept=".png, .jpg, .jpeg"
                                        beforeUpload={
                                            this.handleBeforeUploadImages
                                        }
                                        onPreview={this.handlePreview}
                                        action={`${baseURL}/v1_0/upload`}
                                        onChange={this.handleUploadImages}
                                        fileList={this.state.fileList}
                                    >
                                        {this.state.fileList.length <
                                            this.state.type && (
                                                <PlusOutlined></PlusOutlined>
                                            )}
                                    </Upload>
                                )}
                                <Modal
                                    visible={!!previewImageSrc}
                                    title="图片预览"
                                    footer={null}
                                    onCancel={() =>
                                        this.setState({ previewImageSrc: '' })
                                    }
                                >
                                    <img
                                        alt="example"
                                        style={{ width: '100%' }}
                                        src={previewImageSrc}
                                    />
                                </Modal>
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="内容"
                            name="content"
                            rules={[
                                { required: true, message: '请输入文章内容' },
                            ]}
                        >
                            <ReactQuill
                                theme="snow"
                                style={{ heighe: 200 }}
                                placeholder="请输入文章内容..."
                            ></ReactQuill>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 4 }}>
                            <Space>
                                {id ? (
                                    <Button type="primary" htmlType="subimt">
                                        编辑文章
                                    </Button>
                                ) : (
                                    <Button type="primary" htmlType="subimt">
                                        发布文章
                                    </Button>
                                )}

                                <Button onClick={() => this.issueArtcile(true)}>
                                    存入草稿
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        );
    }
}
